package cn.bonoon.handler;

import java.util.List;

import javax.persistence.EntityManager;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.bonoon.entities.RecycleEntity;

public class DefaultRecycleHandler implements RecycleHandler {
	protected final static Logger log = LoggerFactory.getLogger(DefaultRecycleHandler.class);
	/**
	 * 删除语句
	 */
	private static final String DELETE_SQL = "delete from %s where id = %d and deleted=true";

	/**
	 * 恢复语句
	 */
	private static final String RESUME_SQL = "update %s set deleted = false where id = %d";

	@Override
	public void delete(EntityManager entityManager, RecycleEntity entity) {
		try {
			execute(entityManager, entity, DELETE_SQL);
		} catch (Throwable e) {
			log.error("删除回收站记录异常", e);
			error(entityManager, entity, e);
		}
	}

	@Override
	public void resume(EntityManager entityManager, RecycleEntity entity) {
		try {
			execute(entityManager, entity, RESUME_SQL);
		} catch (Throwable e) {
			log.error("恢复回收站记录异常", e);
			error(entityManager, entity, e);
		}
	}

	private void execute(EntityManager entityManager, RecycleEntity entity, String format) {
		Long eid = entity.getEntityId();
		String ename = entity.getEntityName();
		String ql = String.format(format, ename, eid);
		entityManager.createQuery(ql).executeUpdate();
		entityManager.remove(entity);
	}

	private void error(EntityManager entityManager, RecycleEntity entity, Throwable e) {
		e.printStackTrace();
		try {
			// 记录下异常的情况
			entity.setRemark(e.getMessage());
			entityManager.merge(entity);
		} catch (Throwable t) {
			t.printStackTrace();
			log.error("严重异常!", t);
		}
	}

	@Override
	public void delete(EntityManager entityManager, List<RecycleEntity> entitys) {
		for (RecycleEntity entity : entitys) {
			delete(entityManager, entity);
		}
	}

	@Override
	public void resume(EntityManager entityManager, List<RecycleEntity> entitys) {
		for (RecycleEntity entity : entitys) {
			resume(entityManager, entity);
		}
	}
}
